package com.leyou.gateway.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableConfigurationProperties(CORSProperties.class)//开启配置文件加到类的读取
public class GlobalCORSConfig {

    /*
    * 解决跨域问题：采用cors标准方式
    * 1.SpringMVC提供了CorsFilter   CORS的跨域过滤器
    * 进行一些请求的设置即可
    * 2.SpringBoot 为解决跨域问题，提供了
    * @CrossOrigin 注解
    *
    *
    *
    *
    * */
    @Bean
    public CorsFilter corsFilter(CORSProperties prop) {
        //创建Cors的配置信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许访问的域
        corsConfiguration.setAllowedOrigins(prop.getAllowedOrigins());
        //是否开启cookies
        corsConfiguration.setAllowCredentials(prop.getAllowedCredentials());
        //允许的请求方式
        corsConfiguration.setAllowedMethods(prop.getAllowedMethods());
        //允许的请求头信息
        corsConfiguration.setAllowedHeaders(prop.getAllowedHeaders());
        // 访问有效期
        corsConfiguration.setMaxAge(prop.getMaxAge());
        //添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(prop.getFilterPath(),corsConfiguration);
        //返回新的CORSFilter
        return new CorsFilter(source);
    }
}
